package com.ht.util.ssh;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.io.input.NoCloseInputStream;
import org.apache.sshd.common.util.io.output.NoCloseOutputStream;


public final class SshUtils {

    public static SshResponse runCommand(SshConnection conn, String cmd, long timeout) throws IOException {
        SshClient client = SshClient.setUpDefaultClient();
        try {
            client.start();
            ConnectFuture cf = client.connect("http://192.168.3.49:22");

            ClientSession session = cf.verify().getSession();
            session.addPasswordIdentity(conn.getPassword());
            session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));

            ChannelExec ce = session.createExecChannel(cmd);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayOutputStream err = new ByteArrayOutputStream();
            ce.setOut(out);
            ce.setErr(err);

            ce.open();
            Set<ClientChannelEvent> events = ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
            session.close(false);

            return new SshResponse(out.toString(), err.toString(), ce.getExitStatus());

        } finally {
            client.stop();
        }

    }

    /**
     * 交互式命令发送
     *
     * @param conn
     * @param timeout
     * @throws IOException
     */
    public static void runCommandForInteractive(SshConnection conn, long timeout) throws Exception {
        SshClient client = SshClient.setUpDefaultClient();

        try {
            // Open the client
            client.start();

            ConnectFuture cf = client.connect(conn.getUsername(), conn.getIp(), 22);
            ClientSession session = cf.verify().getSession();
            session.addPasswordIdentity(conn.getPassword());
            session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));

            ChannelShell cs = session.createShellChannel();
            cs.setOut(new NoCloseOutputStream(System.out));
            cs.setErr(new NoCloseOutputStream(System.err));
            cs.setIn(new NoCloseInputStream(System.in));

            cs.open();
            cs.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
            cs.close(false);
            session.close(false);
        } finally {
            client.stop();
        }

    }

    public static void main(String[] args) throws Exception {
        SshConnection conn = new SshConnection("192.168.3.49",22, "root", "123Zx456.//");
        String cmd = "/home/py/aa.py /home/py/3.jpg";
        SshResponse response = runCommand(conn, cmd, 15);

        if(response.getReturnCode()==0){
            //执行成功
            System.out.println("stdOutput=>"+response.getStdOutput());
        }else{
            //执行失败
            System.out.println("errOutput=>"+response.getErrOutput());
        }

    }
}

